﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms;
using System.IO;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Timers;
using System.Collections.ObjectModel;
using Cursors = System.Windows.Input.Cursors;
using IWshRuntime = IWshRuntimeLibrary;
using Force.Crc32;

namespace ZhwangTool
{
    /// <summary>
    /// DumFileCleaner.xaml 的交互逻辑
    /// </summary>
    public partial class DumFileCleaner : System.Windows.Controls.UserControl
    {
        public DumFileCleaner()
        {
            InitializeComponent();
        }

        //nameList 是文件名的list，每个项都是真实存在的文件的文件名。

        List<string> nameList = new List<string>();

        List<string> paths = new List<string>();

        ObservableCollection<MyFileInfo> sourceList_dataGrid1 = new ObservableCollection<MyFileInfo>();

        ObservableCollection<MyFileInfo> sourceList_dataGrid2 = new ObservableCollection<MyFileInfo>();

        private void button1_Click(object sender, RoutedEventArgs e)
        {

            sourceList_dataGrid2.Clear();
            button2.IsEnabled = false;

        }




        private void Button4_Click(object sender, RoutedEventArgs e)
        {
            bool b = false;

            //sourceList_dataGrid1 如为 null 就弹出消息后，停止运行。
            if (sourceList_dataGrid1 == null)
            {
                System.Windows.MessageBox.Show("没有要处理的文件！");
                return;
            }

            //存在选中的文件则继续执行，否则弹出消息后，停止运行。
            foreach (var item in sourceList_dataGrid1)
            {
                if (item.Sign == true)
                {
                    b = true;
                    break;
                }
            }
            //   myFileInfos = groupItem.OrderBy(f => f.Name.Length).Skip(1);

            if (b == false)
            {
                System.Windows.MessageBox.Show("没有要处理的文件！");
                return;
            }

            image1.Source = null;

            List<string> logText = new List<string>();

            List<MyFileInfo> myFileInfos = new List<MyFileInfo>();

            MessageBoxResult res = System.Windows.MessageBox.Show("删除文件后不可恢复，请确认!", "单击确认", MessageBoxButton.YesNo);

            if (res != MessageBoxResult.Yes)
            {
                return;
            }

            FlowDocument fdoc = richTextBox.Document;

            Paragraph paragraph = new Paragraph();

            //从DataGrid1中，移除选定项目

            for (int i = sourceList_dataGrid1.Count - 1; i >= 0; i--)
            {

                if (sourceList_dataGrid1[i] != null)
                {
                    if (sourceList_dataGrid1[i].Sign == true)
                    {
                        int tmpTag = sourceList_dataGrid1[i].Tag;

                        MyFileInfo myFileInfo = sourceList_dataGrid1.Where(p => p.Tag == tmpTag && p.Sign == false)?.First();

                        if (myFileInfo != null)
                        {
                            //fileName 快捷方式指向的文件
                            string fileName = myFileInfo.Name;

                            //快捷方式本身的名称，需要通过要删除的文件名，替换扩展名实现
                            string shortCutName = ReplaceExtension(sourceList_dataGrid1[i].Name, "lnk");

                            CreateShortcut(fileName, shortCutName);

                        }


                        string file_name_to_del = sourceList_dataGrid1[i].Name;

                        if (File.Exists(file_name_to_del))
                        {

                            logText.Add("准备删除文件 ：" + file_name_to_del);

                            Run run1 = new Run("准备删除文件 ：" + file_name_to_del + "\r\n");

                            run1.Foreground = Brushes.Black;

                            paragraph.Inlines.Add(run1);

                            try
                            {
                                File.SetAttributes(file_name_to_del, FileAttributes.Normal);

                                File.Delete(file_name_to_del);

                                //亦是从后删除
                                sourceList_dataGrid1.Remove(sourceList_dataGrid1[i]);

                                //先获取索引，再获取文本内容 

                                logText.Add(":已经顺利删除 ");

                                Run run2 = new Run(":已经顺利删除" + "\r\n");

                                run2.Foreground = Brushes.DarkGreen;

                                run2.FontWeight = FontWeights.Bold;

                                paragraph.Inlines.Add(run2);

                            }
                            catch (Exception)
                            {

                                //throw;

                                //捕获异常，做相应的记录，然后继续执行程序

                                logText.Add(":未能删除+跳过文件");

                                Run run2 = new Run(":未能删除+跳过文件" + "\r\n");

                                run2.Foreground = Brushes.Red;

                                run2.FontWeight = FontWeights.Bold;

                                paragraph.Inlines.Add(run2);

                            }


                        }

                    }

                }

            }
            

            richTextBox.Document.Blocks.Add(paragraph);

            richTextBox.ScrollToEnd();

            //string logFile = null;

            //File.AppendAllLines(logFile, logText);


            //button2.IsEnabled = false;


        }
        //移动重复文件
        private void Button5_Click(object sender, RoutedEventArgs e)
        {
            bool found = false;

            foreach (var item in sourceList_dataGrid1)
            {
                if (item.Sign == true)
                {
                    found = true;
                    break;
                }
            }

            if (found == false)
            {
                System.Windows.MessageBox.Show("没有要处理的文件！");
                return;
            }

            string ob_path = "";

            System.Windows.Forms.FolderBrowserDialog f_Dialog = new FolderBrowserDialog();

            f_Dialog.ShowNewFolderButton = true;

            var diaResult = f_Dialog.ShowDialog();


            if (diaResult == System.Windows.Forms.DialogResult.OK)
            {
                ob_path = f_Dialog.SelectedPath;
            }
            else
            {
                System.Windows.MessageBox.Show("没有选取有效的目标路径，请选取有效目标路径后重试");
                return;
            }
            string tmp_path = "";
            string time_path = DateTime.Now.ToLongDateString();

            if (checkBox1.IsChecked == true)
            {
                tmp_path = System.IO.Path.Combine(ob_path, time_path);
            }
            else
            {
                tmp_path = ob_path;
            }

            if (Directory.Exists(tmp_path) == false)
            {
                DirectoryInfo di = Directory.CreateDirectory(tmp_path);

            }

            List<string> had_files = new List<string>();

            //把目录中既有的文件名加入集合
            foreach (var item in Directory.GetFiles(tmp_path))
            {
                had_files.Add(new FileInfo(item).Name);

            }

            List<string> to_be_move_fullName = new List<string>();

            List<string> moved_shortName = new List<string>();

            string logFile = System.IO.Path.Combine(tmp_path, "logName.txt");

            List<string> moved_Files_Info = new List<string>();

            //将记录在RichtextBox中写出来

            FlowDocument fdoc = richTextBox.Document;

            Paragraph paragraph = new Paragraph();

            for (int i = sourceList_dataGrid1.Count - 1; i >= 0; i--)
            {
                if (sourceList_dataGrid1[i].Sign == true)
                {
                    string fileName = sourceList_dataGrid1[i].Name;

                    FileInfo fi = new FileInfo(fileName);

                    string target_FileName = string.Empty;

                    if (had_files.Contains(fi.Name) == false)
                    {
                        //如果 文件名list中不包含，说明目标路径没有同名文件，不需要重命名

                        had_files.Add(fi.Name);

                        target_FileName = System.IO.Path.Combine(tmp_path, fi.Name);

                    }
                    else
                    {
                        //重名时按照规则生成新名，确保不重复。
                        string tmp_name = ReName(fi.Name, had_files);

                        had_files.Add(tmp_name);

                        target_FileName = System.IO.Path.Combine(tmp_path, tmp_name);

                    }

                    try
                    {
                        //移动成功了再删除listbox中的记录。

            
                        File.Move(fileName, target_FileName);

                        string shortCutName = ReplaceExtension(fileName, "lnk");

                        CreateShortcut(target_FileName, shortCutName);


                        moved_Files_Info.Add(fileName + "\r\n移动为\r\n" + target_FileName);

                        Run run1 = new Run(fileName + "\r\n移动为\r\n" + target_FileName + "\r\n");

                        run1.Foreground = Brushes.Black;

                        paragraph.Inlines.Add(run1);

                        //File.AppendAllText(logFile, fileName + ob_FileName);

                        sourceList_dataGrid1.Remove(sourceList_dataGrid1[i]);


                    }
                    catch (Exception)
                    {

                        //throw;

                        Run run1 = new Run(fi.Name + "\r\n文件被占用 ，跳过文件" + "\r\n");

                        run1.Foreground = Brushes.Red;

                        run1.FontWeight = FontWeights.Bold;

                        paragraph.Inlines.Add(run1);

                        moved_Files_Info.Add(fileName + "\r\n文件被占用 ，跳过文件" + "\r\n");

                    }

                }
            }


            richTextBox.Document.Blocks.Add(paragraph);

            richTextBox.ScrollToEnd();

            File.AppendAllLines(logFile, moved_Files_Info);

            button2.IsEnabled = false;

        }

        private void CheckBox1_Checked(object sender, RoutedEventArgs e)
        {
            checkBox1.Content = DateTime.Now.ToLongDateString();
        }

        private void CheckBox1_Unchecked(object sender, RoutedEventArgs e)
        {
            checkBox1.Content = "创建年月日子目录";
        }



        public static BitmapImage GetImage(string imagePath)
        {
            BitmapImage bitmap = new BitmapImage();
            if (File.Exists(imagePath))
            {
                bitmap.BeginInit();
                bitmap.CacheOption = BitmapCacheOption.OnLoad;
                using (Stream ms = new MemoryStream(File.ReadAllBytes(imagePath)))
                {


                    bitmap.StreamSource = ms;
                    bitmap.EndInit();
                    bitmap.Freeze();
                }
            }
            return bitmap;
        }



        public static List<string> Getfiles(string filepath, string pattern)
        {
            string p = pattern;

            List<string> f_name_list = new List<string>();

            f_name_list = System.IO.Directory.GetFiles(filepath, p, System.IO.SearchOption.AllDirectories).ToList<string>();

            return f_name_list;
        }

        public static string GetMD5HashFromFile(MyFileInfo f_info)
        {
            string fileName = f_info.Name;

            try
            {
                using (FileStream file = new FileStream(fileName, FileMode.Open))
                {
                    System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                    byte[] retVal = md5.ComputeHash(file);

                    StringBuilder sb = new StringBuilder();

                    for (int i = 0; i < retVal.Length; i++)
                    {
                        sb.Append(retVal[i].ToString("x2"));
                    }
                    return sb.ToString();

                }

            }
            catch (Exception ex)
            {

                //throw new Exception("GetMD5HashFromFile() fail,error:文件正在使用中" + ex.Message);

                f_info.ErrMessage = "error: 文件正在使用中" + ex.Message + f_info.Name;

                return string.Empty;

            }
        }

        /// <summary>
        /// 用这个就是直接用文件名对象了
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static uint GetCrc32FromFile(string fileName)
        {

            try
            {

                byte[] zipdata = File.ReadAllBytes(fileName);
                uint crc = Crc32CAlgorithm.Compute(zipdata);
                return crc;

            }
            catch (Exception ex)
            {

                //throw new Exception("GetMD5HashFromFile() fail,error:文件正在使用中" + ex.Message);

                //f_info.ErrMessage = "error: 文件正在使用中" + ex.Message + f_info.Name;

                return 0;

            }
        }

        /// <summary>
        /// 通过文件名获取CRC32值，之所以用myFileInfo对象是为了在对象中保存文件被占用的信息
        /// </summary>
        /// <param name="f_info"></param>
        /// <param name="crc"></param>
        /// <returns></returns>
        public static bool GetCrc32FromFile(MyFileInfo f_info, out uint crc)
        {
            string fileName = f_info.Name;
            try
            {

                byte[] zipdata = File.ReadAllBytes(fileName);
                crc = Crc32CAlgorithm.Compute(zipdata);
                return true;

            }
            catch (Exception ex)
            {

                //throw new Exception("GetMD5HashFromFile() fail,error:文件正在使用中" + ex.Message);

                crc = 0;
                return false;

            }
        }

        public static string GetHash(MyFileInfo f_info)
        {
            string filePath = f_info.Name;

            try
            {
                //创建一个哈希算法对象
                using (HashAlgorithm hash = SHA256.Create())
                {
                    using (FileStream file = new FileStream(filePath, FileMode.Open))
                    {
                        byte[] hashByte = hash.ComputeHash(file);//哈希算法根据文本得到哈希码的字节数组
                        string str = BitConverter.ToString(hashByte);//将字节数组装换为字符串
                        return str;//返回哈希码
                    }
                }
            }
            catch (Exception ex)
            {
                f_info.ErrMessage = "error: 文件正在使用中" + ex.Message + f_info.Name;

                return string.Empty;
            }

        }

        public static string ReName(string str, List<string> in_list)
        {

            string ob_name = "";

            int m = str.LastIndexOf(@".");

            for (int i = 1; i < 500; i++)
            {
                string modify_nm = str.Insert(m, "--" + i.ToString());

                if (in_list.Contains(modify_nm) == false)
                {
                    ob_name = modify_nm;

                    break;
                }

            }
            return ob_name;

        }

        private void ListBox1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var element = (FrameworkElement)sender;
            if (e.ClickCount == 1)
            {
                var timer = new System.Timers.Timer(500);
                timer.AutoReset = false;
                timer.Elapsed += new ElapsedEventHandler((o, ex) => element.Dispatcher.Invoke(new Action(() =>
                {
                    var timer2 = (System.Timers.Timer)element.Tag;
                    timer2.Stop();
                    timer2.Dispose();
                    UIElement_Click(element, e);
                })));
                timer.Start();
                element.Tag = timer;
            }
            if (e.ClickCount > 1)
            {
                var timer = element.Tag as System.Timers.Timer;
                if (timer != null)
                {
                    timer.Stop();
                    timer.Dispose();
                    UIElement_DoubleClick(sender, e);
                }
            }

        }

        private void UIElement_Click(object sender, MouseButtonEventArgs e)
        {





        }

        private void UIElement_DoubleClick(object sender, MouseButtonEventArgs e)
        {

        }

        private void RadioButton7_Checked(object sender, RoutedEventArgs e)
        {
            gridSameFolder.IsEnabled = true;
        }

        private void RadioButton7_Unchecked(object sender, RoutedEventArgs e)
        {
            gridSameFolder.IsEnabled = false;
        }

        //private void CheckBox0_Checked(object sender, RoutedEventArgs e)
        //{

        //    radioButton5.IsEnabled = false;
        //    radioButton6.IsEnabled = false;
        //    radioButton7.IsEnabled = false;



        //}

        //private void CheckBox0_Unchecked(object sender, RoutedEventArgs e)
        //{

        //    radioButton5.IsEnabled = true;
        //    radioButton6.IsEnabled = true;
        //    radioButton7.IsEnabled = true;


        //}

        private void Button6_Click(object sender, RoutedEventArgs e)
        {
            Form form = new AboutBox1();

            form.ShowDialog();
        }

        private void Button7_Click(object sender, RoutedEventArgs e)
        {
            //取消所有选中
            foreach (MyFileInfo item in dataGrid1.Items)
            {
                item.Sign = false;
            }

            richTextBox.Document.Blocks.Clear();


            //var sameFileInfos = from MyFileInfo f in dataGrid1.Items
            //                    group f by f.Crc32 into g
            //                    select g;

            //按照分组码分组文件
            var sameFileInfos = from MyFileInfo f in dataGrid1.Items
                                group f by f.Tag into g
                                orderby g.Key
                                select g;

            IEnumerable<MyFileInfo> myFileInfos = null;

            Paragraph paragraphFirst = new Paragraph();

            Run runFirst = new Run("\r\n我是分隔线-----------------------------------------------------------------------------------------------------\r\n");

            runFirst.Foreground = Brushes.Red;

            paragraphFirst.Inlines.Add(runFirst);

            richTextBox.Document.Blocks.Add(paragraphFirst);


            foreach (var groupItem in sameFileInfos)
            {

                if (radioButton1.IsChecked == true)
                {
                    //按照文件名长短排序，跳过文件名长度最小的，选取其余的，然后设置Sign 为True 选中对象
                    myFileInfos = groupItem.OrderBy(f => f.Name.Length).Skip(1);

                }
                if (radioButton2.IsChecked == true)
                {
                    //按照文件名长短排序，跳过文件名长度最大的，选取其余的，然后设置Sign 为True 选中对象
                    myFileInfos = groupItem.OrderByDescending(f => f.Name.Length).Skip(1);

                }

                if (radioButton3.IsChecked == true)
                {
                    //按照写入时间排序，跳过写入时间最近的，选取其余的，然后设置Sign 为True 选中对象
                    myFileInfos = groupItem.OrderBy(f => new FileInfo(f.Name).LastWriteTime).Skip(1);

                }

                if (radioButton4.IsChecked == true)
                {
                    //按照写入时间排序，跳过写入时间最远的，选取其余的，然后设置Sign 为True 选中对象
                    myFileInfos = groupItem.OrderByDescending(f => new FileInfo(f.Name).LastWriteTime).Skip(1);

                }
                //Regex.Matches(str_f, @"\\").Count

                if (radioButton5.IsChecked == true)
                {
                    //按照路径的层级数排序，跳过路径层次最多的，选取其余的，然后设置Sign 为True 选中对象
                    myFileInfos = groupItem.OrderBy(f => Regex.Matches(f.Name, @"\\").Count).Skip(1);

                }
                if (radioButton6.IsChecked == true)
                {
                    //按照路径的层级数排序，跳过路径层次最少的，选取其余的，然后设置Sign 为True 选中对象
                    myFileInfos = groupItem.OrderByDescending(f => Regex.Matches(f.Name, @"\\").Count).Skip(1);

                }

                //if (radioButton7.IsChecked == true)
                //{
                //    string giveFolder = comBox3.SelectedItem.ToString();
                //    //先判断里面有否有直接在给定文件夹内的重复文件

                //    //再判断里面是全部都直接在给定文件夹内，如果是留一个，如果不是那就把不是的落选，其余选上

                //    //如果都不是那个文件夹得就都落选

                //    //选上的设置Sign为True

                //    List<MyFileInfo> inGiveFolder = new List<MyFileInfo>();
                //    List<MyFileInfo> outGiveFolder = new List<MyFileInfo>();

                //    foreach (var item in groupItem)
                //    {
                //        if (item.GetDirectoryName() == giveFolder)
                //        {
                //            inGiveFolder.Add(item);
                //        }
                //        else
                //        {
                //            outGiveFolder.Add(item);
                //        }

                //    }
                //    if (inGiveFolder.Count == groupItem.Count())
                //    {
                //        myFileInfos = inGiveFolder.OrderBy(f => f.Name.Length).Skip(1);
                //    }
                //    else
                //    {
                //        myFileInfos = inGiveFolder.Select(x => x);
                //    }

                //}

                if (radioButton8.IsChecked == true)
                {
                    string giveFolder = comBox3.SelectedItem.ToString();

                    //先判断里面有否有直接在给定文件夹内的重复文件

                    //再判断里面是全部都直接在给定文件夹内，如果是留一个，如果不是那就把不是的落选，其余选上

                    //如果都不是那个文件夹得就都落选

                    //选上的设置Sign为True

                    List<MyFileInfo> inGiveFolder = new List<MyFileInfo>();
                    List<MyFileInfo> outGiveFolder = new List<MyFileInfo>();

                    foreach (var item in groupItem)
                    {

                        //if (item.Name.StartsWith(giveFolder))
                        //{
                        //    inGiveFolder.Add(item);
                        //}
                        //else
                        //{
                        //    outGiveFolder.Add(item);
                        //}
                        if (giveFolder== System.IO.Path.GetDirectoryName(item.Name))
                        {
                            inGiveFolder.Add(item);
                        }
                        else
                        {
                            outGiveFolder.Add(item);
                        }
                        
                    }
                    if (inGiveFolder.Count == groupItem.Count())
                    {
                        myFileInfos = inGiveFolder.OrderBy(f => f.Name.Length).Skip(1);
                    }
                    else
                    {
                        myFileInfos = inGiveFolder.Select(x => x);
                    }

                }


                if (myFileInfos.Count() > 0)
                {
                    Paragraph paragraph = new Paragraph();

                    foreach (var item in myFileInfos)
                    {
                        item.Sign = true;

                        Run run1 = new Run(item.Name + "\r\n已经标记\r\n");

                        run1.Foreground = Brushes.Black;

                        paragraph.Inlines.Add(run1);

                    }

                    richTextBox.Document.Blocks.Add(paragraph);

                    richTextBox.ScrollToEnd();

                }

            }

            try
            {
                dataGrid1.ScrollIntoView(sourceList_dataGrid1.Where(x => x.Sign == true).First());
            }
            catch (Exception)
            {
                System.Windows.MessageBox.Show("给定的目录及子目录内不存在与其他给定目录内重复的文件");
                //throw;
            }



        }

        private void DataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            MyFileInfo myFileInfo = dataGrid1.SelectedItem as MyFileInfo;


            if (myFileInfo == null)
            {
                return;
            }

            //myFileInfo.Sign = !myFileInfo.Sign;

            string file_Name = myFileInfo.Name;


            if (File.Exists(file_Name))
            {


                FileInfo fi = new FileInfo(file_Name);
                //下边写用richtextbox的情况

                FlowDocument fdoc = richTextBox.Document;

                Paragraph paragraph = new Paragraph();

                Run run1 = new Run("File:" + file_Name + "\r\n");

                run1.Foreground = Brushes.Blue;

                Run run2 = new Run("最后写入时间:" + fi.LastWriteTime.ToString() + "    ");

                run2.Foreground = Brushes.Red;
                run2.FontWeight = FontWeights.Bold;

                Run run3 = new Run("文件创建时间:" + fi.CreationTime.ToString() + "    ");

                run3.Foreground = Brushes.Black;
                run3.FontWeight = FontWeights.Bold;

                //Run run4 = new Run("文件大小:" + fi.Length.ToString());

                //run4.Foreground = Brushes.DarkBlue;
                //run4.FontWeight = FontWeights.Bold;

                paragraph.Inlines.Add(run1);

                paragraph.Inlines.Add(run2);

                paragraph.Inlines.Add(run3);

                //paragraph.Inlines.Add(run4);

                richTextBox.Document.Blocks.Add(paragraph);

                richTextBox.ScrollToEnd();
                scrollViewer1.ScrollToBottom();

                //if (new FileInfo(file_Name).Extension.ToLower().Contains(".jpg"))
                //{

                //    image1.Source = GetImage(file_Name);

                //}



                if (file_Name.ToUpper().EndsWith(".JPG") || file_Name.ToUpper().EndsWith(".PNG") || file_Name.ToUpper().EndsWith(".TIF") || file_Name.ToUpper().EndsWith(".BMP"))
                {
                    sfr.ScaleX = 1;

                    sfr.ScaleY = 1;

                    image1.Source = GetImage(file_Name);

                }
                else
                {
                    image1.Source = null;
                }

            }
        }

        private void DataGrid1_LoadingRow(object sender, DataGridRowEventArgs e)
        {

            MyFileInfo myFileInfo = e.Row.Item as MyFileInfo;
            if (myFileInfo.Tag % 2 == 0)
            {
                e.Row.Background = new SolidColorBrush(Colors.White);
            }
            else
            {
                //e.Row.Background = new SolidColorBrush(Colors.LightGreen);

                e.Row.Background = new SolidColorBrush(Colors.PaleTurquoise);

                //e.Row.Background = new SolidColorBrush(Colors.MediumAquamarine);

                //e.Row.Background = new SolidColorBrush(Colors.GreenYellow);

                //e.Row.Background = new SolidColorBrush(Colors.BlanchedAlmond);

            }

        }

        private void DataGrid1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            MyFileInfo myFileInfo = dataGrid1.SelectedItem as MyFileInfo;

            if (myFileInfo != null)
            {
                string file_Name = myFileInfo.Name;

                string tmp_path = System.IO.Path.GetDirectoryName(file_Name);

                //System.Diagnostics.Process.Start("Explorer", "/select," + file_Name);

                System.Diagnostics.Process.Start(file_Name);

            }

        }

        private void DataGrid2_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = e.Row.GetIndex() + 1;
        }

        private void Button8_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (sourceList_dataGrid1.Count > 0)
                {
                    foreach (var item in sourceList_dataGrid1)
                    {
                        item.Sign = false;
                    }

                }
            }
            catch (Exception)
            {

                //throw;
            }


        }

        private void DataGrid1_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {

            System.Windows.Controls.DataGrid dg = sender as System.Windows.Controls.DataGrid;

            if (dg != null)
            {
                MyFileInfo myFileInfo = dg.SelectedItem as MyFileInfo;

                if (myFileInfo != null && e.Key == Key.Space)
                {
                    myFileInfo.Sign = !myFileInfo.Sign;
                }

            }

        }

        private void ComBox2_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            System.Windows.Controls.Button b = sender as System.Windows.Controls.Button;

        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            progressBar1.Visibility = Visibility.Visible;

            dataGrid1.Visibility = Visibility.Visible;

            dataGrid2.Visibility = Visibility.Hidden;

            List<MyFileInfo> myFileInfos = new List<MyFileInfo>();

            myFileInfos.Clear();

            comBox3.Items.Clear();

            richTextBox.Document.Blocks.Clear();

            //myFilesGroups用来存储按照路径进行分组集合,默认所有文件分到相同的组
            IEnumerable<IGrouping<string, MyFileInfo>> myFilesGroups = from f in sourceList_dataGrid2
                                                                       group f by f.GroupTag into g
                                                                       where g.Count() > 1
                                                                       select g;

            #region 构建myFilesGroups用来存储按照路径进行分组集合

            //按照文件直接路径分组
            if (radioButtonSameFolder.IsChecked == true)
            {
                //只处理相同文件夹内相同文件
                radioButton5.IsEnabled = false;

                radioButton6.IsEnabled = false;

                myFilesGroups = from f in sourceList_dataGrid2
                                group f by f.GetDirectoryName() into g
                                where g.Count() > 1
                                select g;

            }

            //按照文件给定路径分组
            if (radioButtonSameGivenFolder.IsChecked == true)
            {
                radioButton5.IsEnabled = true;

                radioButton6.IsEnabled = true;

                myFilesGroups = from f in sourceList_dataGrid2
                                group f by f.GivenFolder into g
                                where g.Count() > 1
                                select g;

            }

            if (myFilesGroups.ToList().Count == 0)
            {
                return;
            }

            #endregion

            //以下内容与是否选中CheckBox0 无关了！
            //为了列表显示，最好的办法就是保持对象一直都在，一直带有相应的信息

            //myFilesGroup 是 myFilesGroupss中的一个分组 
            //每个myFilesGroups的分组，都存储了多个MyFileInfo对象，其中的Name都是有效的文件名

            //errFileList计划存储存在问题的文件的文件名，实际上应该是跳过的文件的文件名List。最后写出来
            List<string> errFileList = new List<string>();

            errFileList.Clear();

            int tagInt = 0;

            foreach (var myFilesGroup in myFilesGroups)
            {
                //每个文件夹内重复文件的数量
                int sameFileCount = 0;

                //Dictionary<MyFileInfo, long> 中，Key是MyFileInfo对象，Value是对应的大小信息，

                Dictionary<MyFileInfo, long> dic_of_files = new Dictionary<MyFileInfo, long>();

                //cur_deal_folder 当前正在处理的文件夹，用于在RichTextBox1 输出相关信息。

                string cur_deal_folder = myFilesGroup.ToList()[0].GetDirectoryName();

                //将所有文件的文件名称和文件大小都加进字典中；

                foreach (var item in myFilesGroup)
                {
                    //key 是 MyFileInfo  value是对应的大小信息
                    dic_of_files.Add(item, item.Size);

                }

                //dic_of_files.OrderBy(x => x.Value) 先按照文件Size排序，再进行查找，将小文件放在开头,实际上没有必要
                //var groups = from x in dic_of_files.OrderBy(x => x.Value)
                //groups 是一种匿名类对象的分组，匿名类有两个属性，是Value和Items，Items就是文件名的List。 

                var groups = from x in dic_of_files.OrderBy(x => x.Value)
                             group x by x.Value into g
                             where g.Count() > 1
                             select new { Value = g.Key, Items = g.Select(x => x.Key) };

                progressBar1.Maximum = groups.Count();

                progressBar1.Value = 0;

                //处理具有相同文件大小的每一个分组，通过Crc32进一步判断是否相同文件
                foreach (var group in groups)
                {

                    //一个记录MyFileInfo和crc32值的字典，crc32值作为value，MyFileInfo为key

                    Dictionary<MyFileInfo, uint> dic_of_simeSize = new Dictionary<MyFileInfo, uint>();

                    dic_of_simeSize.Clear();

                    foreach (var item in group.Items)
                    {
                        uint tmp_uint = 0;

                        bool b = GetCrc32FromFile(item, out tmp_uint);

                        if (b == true)
                        {
                            item.Crc32 = tmp_uint;

                            dic_of_simeSize.Add(item, item.Crc32);

                        }
                        else
                        {
                            errFileList.Add(item.Name + "在获取Crc32值时发生错误，一般是由于文件正在使用造成的错误，程序会跳过对这个文件。");
                        }

                    }

                    //  var groups_same_Crc32 = dic_of_simeSize.OrderBy(x => x.Value)
                    //.GroupBy(x => x.Value).Select(g => new { Value = g.Key, Items = g.Select(x => x.Key) });
                    //通过linq进行分组，将Crc32值一样的分到一组，判定为相同文件

                    var groups_same_Crc32 = from x in dic_of_simeSize.OrderBy(x => Regex.Matches(x.Key.Name, @"\\").Count)
                                            group x by x.Value into g
                                            where g.Count() > 1
                                            select new { Value = g.Key, Items = g.Select(x => x.Key) };

                    //把每组判定为相同的文件名称写到列表中，并添加分隔符以便后续处理

                    foreach (var group_sameCrc32 in groups_same_Crc32)
                    {

                        foreach (var item in group_sameCrc32.Items)
                        {

                            //这个List中记录的对象是真实存在的重复文件信息
                            item.Tag = tagInt;

                            myFileInfos.Add(item);

                            sameFileCount++;

                        }

                        tagInt++;

                    }
                    //更新进度条
                    Dispatcher.Invoke(new Action<System.Windows.DependencyProperty, object>(progressBar1.SetValue), System.Windows.Threading.DispatcherPriority.Background, new object[] { System.Windows.Controls.ProgressBar.ValueProperty, Convert.ToDouble(progressBar1.Value + 1) });

                }

                //System.Windows.MessageBox.Show("重复文件查找完毕，共有"+k.ToString()+"个重复文件");
                //k>0 表示当前文件夹下存在重复文件，在RichTextBox中输出相关信息
                if (sameFileCount > 0)
                {
                    Paragraph paragraph = new Paragraph();

                    Run run1 = new Run(cur_deal_folder + "\r\n文件夹内夹共有" + sameFileCount.ToString() + "个重复文件");

                    run1.Foreground = Brushes.Black;

                    run1.FontWeight = FontWeights.Bold;

                    paragraph.Inlines.Add(run1);

                    richTextBox.Document.Blocks.Add(paragraph);

                }


            }

            //将重复文件的直接文件路径添加到comgbox中

            List<string> addToCombox3 = new List<string>();

            //将取得的需要处理的重复文件信息按照Crc32值分组
            var sourceItems = from f in myFileInfos
                              group f by f.Tag into g
                              select g;

            int m = 0;

            sourceList_dataGrid1.Clear();

            foreach (var group in sourceItems)
            {
                foreach (var item in group.OrderBy(x => x.Tag).ThenBy(x => Regex.Matches(x.Name, @"\\").Count).ThenBy(x => x.Name.LastIndexOf(".") - x.Name.LastIndexOf("\\")))
                {
                    //item.Tag = m;

                    sourceList_dataGrid1.Add(item);
                }

                m++;

            }



            if (sourceList_dataGrid1.Count > 0)
            {
                groupBox1.IsEnabled = true;

                radioButton1.IsChecked = true;

                button7.IsEnabled = true;

            }


            foreach (var item in sourceList_dataGrid1)
            {

                string folder = item.GetDirectoryName();

                if (addToCombox3.Contains(folder) == false)
                {
                    addToCombox3.Add(folder);

                }

            }

            //将路径list按照路径的深度排序，添加到comBox3中
            comBox3.Items.Clear();
            foreach (var item in addToCombox3.OrderBy(x => Regex.Matches(x, @"\\").Count))
            {
                comBox3.Items.Add(item);

            }

            comBox3.SelectedIndex = 0;

            dataGrid1.ItemsSource = sourceList_dataGrid1;



            #region 如果存在取得Crc32数值时发生错误的文件，将相关信息写到richTextBox中

            //如果存在取得Crc32数值时发生错误的文件，将相关信息写到richTextBox中
            if (errFileList.Count > 0)
            {
                foreach (var item in errFileList)
                {
                    Paragraph paragraph = new Paragraph();

                    Run run1 = new Run(item);

                    run1.Foreground = Brushes.Red;

                    run1.FontWeight = FontWeights.Bold;

                    paragraph.Inlines.Add(run1);

                    richTextBox.Document.Blocks.Add(paragraph);
                }

            }
            else
            {
                Paragraph paragraph = new Paragraph();

                Run run1 = new Run("所有重复文件都顺利的添加进了列表中");

                run1.Foreground = Brushes.Red;

                run1.FontWeight = FontWeights.Bold;

                paragraph.Inlines.Add(run1);

                richTextBox.Document.Blocks.Add(paragraph);

            }


            #endregion


            progressBar1.Value = 0;

            progressBar1.Visibility = Visibility.Hidden; ;

        }

        private void ComBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (button2 != null)
            {
                button2.IsEnabled = false;
            }

        }

        private void ComBox2_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (button2 != null)
            {
                button2.IsEnabled = false;
            }
        }

        private void Grid_PreviewCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            System.Windows.Controls.DataGrid grid = (System.Windows.Controls.DataGrid)sender;

            if (e.Command == System.Windows.Controls.DataGrid.DeleteCommand)
            {
                if (System.Windows.MessageBox.Show(String.Format("Would you like to delete {0}", (grid.SelectedItem as MyFileInfo).Name), "Confirm Delete", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    sourceList_dataGrid2.Remove(grid.SelectedItem as MyFileInfo);

                    try
                    {

                        File.SetAttributes((grid.SelectedItem as MyFileInfo).Name, FileAttributes.Normal);

                        File.Delete((grid.SelectedItem as MyFileInfo).Name);

                        Paragraph paragraph = new Paragraph();

                        Run run2 = new Run("直接删除选定文件" + (grid.SelectedItem as MyFileInfo).Name + "\r\n");

                        run2.Foreground = Brushes.DarkGreen;

                        run2.FontWeight = FontWeights.Bold;

                        paragraph.Inlines.Add(run2);

                        richTextBox.Document.Blocks.Add(paragraph);

                        richTextBox.ScrollToEnd();

                    }
                    catch (Exception)
                    {
                        Paragraph paragraph = new Paragraph();

                        Run run2 = new Run("尝试删除文件" + (grid.SelectedItem as MyFileInfo).Name + "失败" + "\r\n");

                        run2.Foreground = Brushes.Red;

                        run2.FontWeight = FontWeights.Bold;

                        paragraph.Inlines.Add(run2);

                        richTextBox.Document.Blocks.Add(paragraph);

                        richTextBox.ScrollToEnd();

                        e.Handled = true;
                    }

                    //e.Handled = true;
                }
                else
                {
                    e.Handled = true;
                }


            }
        }

        private void Image1_MouseWheel(object sender, MouseWheelEventArgs e)
        {

            //Point centerPoint = e.GetPosition(sender as IInputElement);

            ////centerPoint = ((Image)sender).p

            //this.sfr.CenterX = centerPoint.X;
            //this.sfr.CenterY = centerPoint.Y;
            if (sfr.ScaleX < 0.3 && sfr.ScaleY < 0.3 && e.Delta < 0)
            {
                return;
            }
            sfr.ScaleX += (double)e.Delta / 3500;
            sfr.ScaleY += (double)e.Delta / 3500;

        }

        private void Image1_MouseDown(object sender, MouseButtonEventArgs e)
        {
            ((Image)sender).Cursor = Cursors.Hand;


        }

        private void Image1_MouseUp(object sender, MouseButtonEventArgs e)
        {
            ((Image)sender).ReleaseMouseCapture();
            ((Image)sender).Cursor = Cursors.Arrow;
        }

        private void Image1_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                // 鼠标位置
                Point point = e.GetPosition(image1);
                Image rec = (Image)sender;
                double marginLeft = point.X - rec.Width / 2;
                double marginTop = point.Y - rec.Height / 2;

            }
        }

        //鼠标是否按下
        bool _isMouseDown = false;
        //鼠标按下的位置
        Point _mouseDownPosition;
        //鼠标按下控件的位置
        Point _mouseDownControlPosition;

        private void Button_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            var c = sender as UIElement;
            _isMouseDown = true;
            _mouseDownPosition = e.GetPosition(this);
            var transform = c.RenderTransform as TranslateTransform;
            if (transform == null)
            {
                transform = new TranslateTransform();
                c.RenderTransform = transform;
            }
            _mouseDownControlPosition = new Point(transform.X, transform.Y);
            c.CaptureMouse();
        }

        private void Button_PreviewMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (_isMouseDown)
            {
                var c = sender as UIElement;
                var pos = e.GetPosition(this);
                var dp = pos - _mouseDownPosition;
                var transform = c.RenderTransform as TranslateTransform;
                transform.X = _mouseDownControlPosition.X + dp.X;
                transform.Y = _mouseDownControlPosition.Y + dp.Y;
            }
        }

        private void Button_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            var c = sender as UIElement;
            _isMouseDown = false;
            c.ReleaseMouseCapture();
        }



        private void tabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int index = (sender as System.Windows.Controls.TabControl).SelectedIndex;
           
            //win2 w2 = new win2();
            //win3 w3 = new win3();
            //win4 w4 = new win4();
            switch (index)
            {
                case 0:

                    break;
                    //case 1:
                    //    this.p2.Children.Add(w2);
                    //    break;
                    //case 2:
                    //    this.p3.Children.Add(w3);
                    //    break;
                    //case 3:
                    //    this.p4.Children.Add(w4);
                    //    break;

            }
        }


        List<string> emptyDirs = new List<string>();



        static List<string> GetEmptyFolders(string path)
        {
            List<string> emptyFolders = new List<string>();
            DirectoryInfo dirInfo = new DirectoryInfo(path);
            FileSystemInfo[] fileSystemInfos = dirInfo.GetFileSystemInfos();
            foreach (FileSystemInfo fileSystemInfo in fileSystemInfos)
            {
                if (fileSystemInfo is DirectoryInfo)
                {
                    DirectoryInfo dir = fileSystemInfo as DirectoryInfo;

                    try
                    {
                        if (dir.GetFiles().Length == 0 && dir.GetDirectories().Length == 0)
                        {
                            emptyFolders.Add(dir.FullName);
                        }
                        emptyFolders.AddRange(GetEmptyFolders(dir.FullName));

                    }
                    catch (Exception)
                    {
                        continue;
                        //throw;
                    }



                }
            }
            return emptyFolders;
        }

        private void TextBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {

        }



        private void Button21_Click(object sender, RoutedEventArgs e)
        {
            if (folderList.Items.Count == 0)
            {
                return;
            }




            #region 控制文件大小变量赋值

            int long_size = 0;

            switch (comBox2.SelectedIndex)
            {
                case 0:
                    long_size = 0;
                    break;
                case 1:
                    long_size = 1024 * 10;
                    break;
                case 2:
                    long_size = 1024 * 100;
                    break;
                case 3:
                    long_size = 1024 * 1024;
                    break;
                case 4:
                    long_size = 1024 * 1024 * 10;
                    break;
                case 5:
                    long_size = 1024 * 1024 * 100;
                    break;
                case 6:
                    long_size = 1024 * 1024 * 1024;
                    break;

                default:
                    long_size = 0;
                    break;
            }
            #endregion

            sourceList_dataGrid1.Clear();

            sourceList_dataGrid2.Clear();

            dataGrid1.Visibility = Visibility.Hidden;

            dataGrid2.Visibility = Visibility.Visible;

            progressBar1.Value = 0;

            richTextBox.Document.Blocks.Clear();

            string p = "*";

            List<MyFileName> allFileNameList = new List<MyFileName>();

            foreach (var item in folderList.Items)
            {
                string path = item as string;

                //如path不是有效路径，那就跳过当前path
                if (Directory.Exists(path) == false)
                {
                    continue;
                }

                List<MyFileName> myFileNames = new List<MyFileName>();

                List<string> nameListInCurPath = new List<string>();

                List<string> tmp_names = new List<string>();

                try
                {
                    //nameListInCurPath = Getfiles(path, p);
                    nameListInCurPath = Tools.Getfiles(path, p, true);
                    
                }
                catch (Exception)
                {
                    System.Windows.MessageBox.Show("获取文件名列表出错，存在无权限访问的文件夹，或者出现其他问题，请选择更具体的文件夹");
                    return;
                }


                switch (comBox1.SelectedIndex)
                {
                    case 0:
                        break;
                    case 1:
                        nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".dwg")).ToList<string>();
                        break;
                    case 2:
                        nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".xls") || x.EndsWith(".xlsx")).ToList<string>();
                        break;
                    case 3:
                        nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".ppt") || x.EndsWith(".pptx")).ToList<string>();
                        break;
                    case 4:
                        nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".doc") || x.EndsWith(".docx")).ToList<string>();
                        break;
                    case 5:
                        nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".pdf")).ToList<string>();
                        break;
                    case 6:
                        nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".rar") || x.EndsWith(".zip") || x.EndsWith(".7z")).ToList<string>();
                        break;
                    case 7:
                        nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".doc") || x.EndsWith(".docx") || x.EndsWith(".dwg") || x.EndsWith(".ppt") ||
                         x.EndsWith(".pptx") || x.EndsWith(".xls") || x.EndsWith(".xlsx") || x.EndsWith("*.pdf")).ToList<string>();
                        break;
                    case 8:
                        nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".jpg") || x.EndsWith(".JPG") || x.EndsWith(".BMP") || x.EndsWith(".bmp") || x.EndsWith(".png") || x.EndsWith(".PNG") ||
                        x.EndsWith(".jpeg") || x.EndsWith(".JPEG")).ToList<string>();
                        break;
                    case 9:
                        nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".bak")).ToList<string>();
                        break;

                    default:
                        break;
                }
   
                foreach (string fileName in nameListInCurPath)
                {
                    MyFileName myFileName = new MyFileName();

                    myFileName.FileName = fileName;

                    myFileName.GivenFolder = path;

                    allFileNameList.Add(myFileName);

                }

            }



            //前面把给定类型的文件名都加进了结合中，下一步控制文件的大小，将大小满足要求的文件名保留在List中

            List<MyFileInfo> tmp_list = new List<MyFileInfo>();

            for (int i = 0; i < allFileNameList.Count; i++)
            {
                string path = "";

                MyFileInfo m_file = new MyFileInfo(allFileNameList[i].FileName, allFileNameList[i].GivenFolder);

                m_file.Size = new FileInfo(allFileNameList[i].FileName).Length;

                //大于给定大小的文件被加入dic_of_files中，用于后续处理。
                if (m_file.Size >= long_size)
                {
                    tmp_list.Add(m_file);
                }

            }

            //sourceList_dataGrid2.Clear();

            foreach (var item in tmp_list.OrderBy(x => Regex.Matches(x.Name, @"\\").Count).ThenBy(x => x.Name.LastIndexOf(".") - x.Name.LastIndexOf("\\")))
            {
                MyFileInfo myFileInfo = item as MyFileInfo;

                if (myFileInfo != null)
                {
                    sourceList_dataGrid2.Add(myFileInfo);
                }

            }

            dataGrid2.ItemsSource = sourceList_dataGrid2;



            //dataGrid2.ScrollIntoView(dataGrid2.Items[dataGrid2.Items.Count - 1]);

            #region 输出满足要求的文件数信息，如果存在满足要求的文件，将button2设置为enable

            if (sourceList_dataGrid2.Count > 0)
            {
                button2.IsEnabled = true;

                FlowDocument fdoc = richTextBox.Document;

                Paragraph paragraph = new Paragraph();

                Run run1 = new Run("给定路径下共有" + tmp_list.Count.ToString() + "个满足要求的文件");

                run1.Foreground = Brushes.Blue;

                paragraph.Inlines.Add(run1);

                richTextBox.Document.Blocks.Add(paragraph);
            }
            else
            {
                FlowDocument fdoc = richTextBox.Document;

                Paragraph paragraph = new Paragraph();

                Run run1 = new Run("给定路径下没有满足要求的个文件");

                run1.Foreground = Brushes.Blue;

                paragraph.Inlines.Add(run1);

                richTextBox.Document.Blocks.Add(paragraph);

            }

            #endregion








            //paths.Clear();
            //sourceList_dataGrid2.Clear();
            //button2.IsEnabled = false;
            //textBox1.Text = string.Empty;

        }



        private void AddFolderbButton_Click_1(object sender, RoutedEventArgs e)
        {
            string lastFolder = string.Empty;

            if (folderList.Items.Count > 0)
            {
                lastFolder = folderList.Items[folderList.Items.Count - 1] as string;
            }

            var folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();

            folderBrowserDialog1.RootFolder = Environment.SpecialFolder.Desktop;

            if (Directory.Exists(lastFolder))
            {

                folderBrowserDialog1.SelectedPath = lastFolder;

            }


            folderBrowserDialog1.Description = "请选取需要处理的文件夹";

            //folderBrowserDialog1.SelectedPath = Environment.SpecialFolder.MyDocuments.ToString();

            folderBrowserDialog1.ShowNewFolderButton = false;

            var diaResult = folderBrowserDialog1.ShowDialog();

            if (diaResult == System.Windows.Forms.DialogResult.OK)
            {
                string tmpPath = folderBrowserDialog1.SelectedPath;

                bool needAdd = true;

                foreach (string item in folderList.Items)
                {
                    if (item.StartsWith(tmpPath) || tmpPath.StartsWith(item))
                    {
                        needAdd = false;

                        System.Windows.MessageBox.Show("选中路径不会添加进列表", "注意，选中的路径与列表中路径存在彼此包含关系", MessageBoxButton.OK);

                        break;
                    }

                }

                if (needAdd == true)
                {
                    folderList.Items.Add(tmpPath);
                }

            }
            else
            {
                return;
            }

        }

        bool isSubDirectory(string candidate, string parent)
        {
            var candidateInfo = new DirectoryInfo(candidate);
            var parentInfo = new DirectoryInfo(parent);

            while (candidateInfo.Parent != null)
            {
                if (candidateInfo.Parent.FullName.Equals(parentInfo.FullName))
                {
                    return true;
                }

                candidateInfo = candidateInfo.Parent;
            }

            return false;
        }



        private void ClearFolderbButton_Click(object sender, RoutedEventArgs e)
        {
            folderList.Items.Clear();
            sourceList_dataGrid2.Clear();
            sourceList_dataGrid1.Clear();
            button2.IsEnabled = false;

        }

        List<string> fileSelects = new List<string>();






        /// <summary>
        /// 获取文件的大小
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public int GetFileSize(string path)
        {
            System.IO.FileInfo fileInfo = null;
            try
            {
                fileInfo = new System.IO.FileInfo(path);

                fileInfo.Refresh();
            }
            catch
            {
                return 0;
            }
            if (fileInfo != null && fileInfo.Exists)
            {
                return (int)System.Math.Ceiling(fileInfo.Length / 1024.0);
            }
            else
            {
                return 0;
            }
        }


        /// <summary>
        /// 创建给定文件的快捷方式
        /// </summary>
        /// <param name="targetPath">快捷方式指向的文件路径</param>
        /// <param name="shortcutPath">快捷方式本身的路径</param>
        public static void CreateShortcut(string targetPath, string shortcutPath)
        {
            IWshRuntime.WshShell shell = new IWshRuntime.WshShell();
            IWshRuntime.IWshShortcut shortcut = (IWshRuntime.IWshShortcut)shell.CreateShortcut(shortcutPath);

            // 设置快捷方式目标
            shortcut.TargetPath = targetPath;

            // 保存快捷方式
            shortcut.Save();
        }

        static string ReplaceExtension(string fileName, string newExtension)
        {
            int dotIndex = fileName.LastIndexOf('.');
            if (dotIndex == -1)
            {
                return fileName + "." + newExtension;
            }
            else
            {
                return fileName.Substring(0, dotIndex) + "." + newExtension;
            }
        }

        private void Border_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            //Point centerPoint = e.GetPosition(sender as IInputElement);

            ////centerPoint = ((Image)sender).p

            //this.sfr.CenterX = centerPoint.X;
            //this.sfr.CenterY = centerPoint.Y;
            if (sfr.ScaleX < 0.3 && sfr.ScaleY < 0.3 && e.Delta < 0)
            {
                return;
            }
            sfr.ScaleX += (double)e.Delta / 3500;
            sfr.ScaleY += (double)e.Delta / 3500;
            
        }

        private void FolderList_Drop(object sender, System.Windows.DragEventArgs e)
        {
            string[] paths = (string[])e.Data.GetData(System.Windows.DataFormats.FileDrop);
     
            string folderPath = paths[0];

            if (folderList.Items.Contains(folderPath)==false)
            {
                folderList.Items.Add(folderPath);

            }



     
            
        }
    }
}
